package com.alliky.core.net.converter;

import com.alliky.core.net.HandleException;
import com.alliky.core.net.ResponseThrowable;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @Author: wxianing
 * @CreateDate: 2022/7/13 23:29
 * @Description: java类作用描述
 */
public class CustomResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String jsonString = value.string();
        try {
            JSONObject object = new JSONObject(jsonString);
            int code = object.getInt("code");
            if (code != 0) {
                String message = object.getString("message");
                //异常处理
                throw new ResponseThrowable(code, message);
            }
            return adapter.fromJson(object.getString("data"));
        } catch (JSONException e) {
            e.printStackTrace();
            //数据解析异常
            throw new ResponseThrowable(HandleException.ERROR.PARSE_ERROR);
        } finally {
            value.close();
        }
    }
}
